/**
 * 
 */
package com.wubo.sec.service.impl;

import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import com.wubo.sec.bean.UserRoleRelate;
import com.wubo.sec.config.LangUtil;
import com.wubo.sec.event.RoleEvent;
import com.wubo.sec.log.LogHelper;
import com.wubo.sec.log.LogState;
import com.wubo.sec.model.Role;
import com.wubo.sec.model.User;
import com.wubo.sec.service.IUserRoleService;
import com.wubo.sec.util.ArrayUtils;
import com.wubo.spring.hibernate.BaseHibernateDao;

/**
 * @author WuBo
 * @CreateDate 2010-8-8
 * @version 1.0.01
 */
@Service
@SuppressWarnings("unchecked")
public class UserRoleService implements IUserRoleService, ApplicationListener<ApplicationEvent>  {

	@Autowired
	private BaseHibernateDao dao;
	
	public BaseHibernateDao getDao() {
		return dao;
	}

	public void setDao(BaseHibernateDao dao) {
		this.dao = dao;
	}

	public List<String> getRoleCodes(String username) {
		return dao.find("select r.code from Role r inner join r.users u where u.username = ?", new Object[]{username});
	}
	
	public void relate(UserRoleRelate relate){
		String username = relate.getUsername();
		String[] roleCodes = relate.getRoleCodes();
		
		User user = dao.get(User.class, username);
		
		StringBuilder sb = new StringBuilder();
		if(roleCodes != null && roleCodes.length > 0){
			List<Role> roles = dao.find("from Role r where r.code in ("+ArrayUtils.split(roleCodes, ",", "'")+")");
			
			for(int i=0; i<roles.size(); i++){
				if(i>0){sb.append(",");}
				Role temp = roles.get(i);
				if(LogState.isLogCode()){
					sb.append(temp.getCode()+"("+temp.getRoleName()+")");	
				}else{
					sb.append(temp.getRoleName());	
				}
							
			}
			user.setRoles(new HashSet<Role>(roles));
		}else{
			user.setRoles(null);
		}
		
		dao.update(user);

		if(LogState.isLogCode()){
			LogHelper.actionLog(LangUtil.get("RelateUserRole"), LangUtil.get("UserRoleDetail", username+"("+user.getUserText()+")", sb.toString()));
		}else{
			LogHelper.actionLog(LangUtil.get("RelateUserRole"), LangUtil.get("UserRoleDetail", user.getUserText(), sb.toString()));
		}
		
	
	}
	
	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof RoleEvent){
			RoleEvent roleEvent = (RoleEvent) event;
			if( roleEvent.getType() == RoleEvent.DELETE ){
				dao.executeSQL("DELETE FROM SEC_USER_ROLE WHERE ROLE_REL = ?", roleEvent.getEntity().getCode());
			}
		}
	}
}
